package com.demo.security.service;

import com.demo.security.entity.UserDetail;
import com.demo.services.user.RoleService;
import com.demo.services.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.stream.Collectors;

@Service
public class JpaUserService implements UserDetailsService {
    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Override
    public UserDetail loadUserByUsername(String username)
            throws UsernameNotFoundException {
        return (UserDetail) userService.findByAccount(username)
                .map(user -> User.builder()
                        .username(user.getAccount())
                        .password(user.getPassword())
                        .roles(user.getRoles())
                        .accountLocked(user.getStatus() >=1) // 账户锁定状态
                        .build())
                .orElseThrow(() -> new UsernameNotFoundException("用户不存在"));
    }
}
